layui.use(['form', 'layedit', 'laydate', 'jquery'], function(){
  var form = layui.form
  ,layer = layui.layer
  ,layedit = layui.layedit
  ,laydate = layui.laydate
  ,$ = layui.$;

   //自定义验证规则
  form.verify({
    pass: [
      /^[\S]{6,12}$/
      ,'密码必须6到12位，且不能出现空格'
    ]
    ,re_pass: function(value,item){
      if(value != $('input[name="password"]').val()){
        return '两次密码不一致'
      }
    }
    ,verify:[
      /^[\d]{6}$/
      ,'验证码必须6位数字'
    ]
  });

    //监听提交
  form.on('submit(register)', function(data){
    // layer.alert(JSON.stringify(data.field), {
    //   title: '最终的提交信息'
    // })
    $.post('/user/emailregister/',data.field, function (data) {
      if (data.code == 4001 || data.code == 4003){
        layer.msg(data.msg, {icon: 5});
        return false;
      }
      if (data.code == 0){
        location.href = '/static/login.html';
      }
    });
    return false;
  });
  let expiry_time = 60;
  let time_count = expiry_time;
  let flag = true; // true,可以点击，false，不可以点击
  let local_time_count = localStorage.getItem('time_count');

  function send_mail_style() {
      $('#send_mail').addClass('layui-btn-disabled'); // 按钮禁用，样式
      flag = false;
    // 实现倒计时
      let timeout = function(){
        $('#send_mail').text(time_count + '秒后重试');
        if (time_count == 0){
          clearInterval(setTimeout);
          flag = true;
          $('#send_mail').removeClass('layui-btn-disabled');
          $('#send_mail').text('发送验证码');
          time_count = expiry_time;
          localStorage.removeItem('time_count');
          return false;//结束
        }
        time_count--;
        localStorage.setItem('time_count',time_count);
      }
      timeout();
      setTimeout = setInterval(timeout, 1000);
    }
    if(local_time_count){ // 如果有值，禁用发送验证码
        time_count = local_time_count; // 防止页面刷新变量重置
        send_mail_style();
    }
  // 发送验证码
  $('#send_mail').click(function(){
    let email = $('input[name="email"]').val();
    // 是否有参数
    if (!email){
      layer.msg('请输入邮箱',{icon: 5});
      return false;
    }
    // 参数格式是否正确
    let reg = /^([a-zA-Z0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,5})$/
    if (!reg.test(email)){
      layer.msg('邮箱格式不正确',{icon: 5});
      return false;
    }
    // 发送验证码
    if (!flag){
      layer.msg('请稍后重试',{icon: 5})
      return false;
    }
    $.post('/user/emailverify/',{email:email},function (data) {
      console.log(data);
      if (data.code == 4002){
        layer.msg('请稍后重试',{icon: 5});
        return false;
      }
    });
    send_mail_style();
  });
});